﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using log4net;
using System.Data.SqlClient;

public partial class shiftGrant : System.Web.UI.Page
{
    //inject EmployeeBLL
    private IEmployeeBLL empBLL = Factory<IEmployeeBLL>.CreateInstance();

    //Inject log4net
    private static readonly ILog logger = LogManager.GetLogger(typeof(shiftGrant).Name);

    //inject shiftBLL
    private IShiftBLL shiftBLL = Factory<IShiftBLL>.CreateInstance();

   

    protected void Page_Load(object sender, EventArgs e)
    {
        string id = "";
        if (this.Context.Items["employeeID"] != null)
        {
            id = this.Context.Items["employeeID"].ToString();
            if (!Page.IsPostBack)
            {
                Inits(id);
            }
        }

        if (ViewState["Id"] != null)
            LoadGrid(new Guid(ViewState["Id"].ToString()));
        
    }


    /// <summary>
    /// Init form
    /// </summary>
    /// <param name="id"></param>
    private void Inits(String id)
    {
        try
        {
            Employee emp = null;
            if (Utils.IsGuid(id))
            {
                emp = empBLL.GetById(new Guid(id));
                //set to control
                lblCode.Text = emp.Code;
                lblFullName.Text = emp.FirstName + Constants.SPACE + emp.LastName;
                lblUser.Text = emp.UserName;
                lblPosition.Text = emp.Position;
                //set employeeId to hidden
                hdnEmployeeId.Value = id;
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }

        //register javascript
        btnSave.Attributes.Add("onmouseover", "this.src='images/luu_hover.gif'");
        btnSave.Attributes.Add("onmouseout", "this.src='images/luu.gif'");
        //btnReset.Attributes.Add("onmouseover", "this.src='images/xoa_hover.gif'");
        //btnReset.Attributes.Add("onmouseout", "this.src='images/xoa.gif'");

        //load into year ddl
        LoadYearDDL();
        //Load into grid
        LoadGrid(new Guid(id));

    }


    /// <summary>
    /// Get no shift
    /// </summary>
    /// <returns></returns>
    private int GetNoShift()
    {
        int temp = 0;
        try
        {
            temp= shiftBLL.GetShiftActive().Count;
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
           
        }
        return temp;
    }

    /// <summary>
    /// Load data to Grid
    /// </summary>
    /// <param name="id"></param>
    private void LoadGrid(Guid id)
    {
        //save id to viewstate
        ViewState["Id"] = id;

        int noShift = GetNoShift();
        DataTable dt = null;
        int intMonth = int.Parse(ddlMonth.SelectedValue);
        int intYear = int.Parse(ddlYear.SelectedValue);
        DateTime monthYearDDL = new DateTime(intYear, intMonth, 1);

        try
        {
            dt = shiftBLL.LoadGrantShiftByEmployee(id, monthYearDDL);
            for (int i = dt.Columns.Count; i > noShift + 1; i--)
            {
                dt.Columns.RemoveAt(i-1);
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
            lblMsg.Visible=true;
        }

       
        for (int i = 1; i <= DateTime.DaysInMonth(intYear,intMonth); i++)
        {
            DateTime currentDate = new DateTime(intYear, intMonth, i);
            DataRow[] rows = dt.Select(String.Format("Date='{0}'", currentDate.ToString(Constants.DATE_PATTERN)));            
            if (rows.Length == 0)
            {
                DataRow row = dt.NewRow();
                row[0] = currentDate.ToString(Constants.DATE_PATTERN);
                for (int j = 1; j <=noShift; j++)
                {
                    if (j == 1)
                        row[j] = "EMPTY_" + 0;
                    else
                        row[j] = 0;
                }                
                dt.Rows.Add(row);
            }
        }

        DataView dv = dt.DefaultView;
        dv.Sort = "Date ASC";
        dt = dv.ToTable();
        //bind to GridView
        gvShift.DataSource = dt;
        gvShift.DataBind();
    }


   

    /// <summary>
    /// Save data to DB
    /// </summary>
    private void Save()
    {
        
        //get EmployeeId from session
        Guid employeeId=Guid.Empty;
        if (Session["Employee"]!=null)
	    {
    		Employee emp=(Employee)Session["Employee"];
            employeeId =emp.Id;
	    }

        List<EmployeeShift> list = new List<EmployeeShift>();
        EmployeeShift empShift=null;
        foreach (GridViewRow row in gvShift.Rows)
        {
            
            //find hidden which saved employeeshiftId
            HiddenField hdnID = (HiddenField)row.Cells[1].FindControl("hdnId");
            //init and set to BO
            empShift = new EmployeeShift();
            if (Utils.IsGuid(hdnID.Value))
                empShift.Id = new Guid(hdnID.Value);
            else
                empShift.Id = Guid.Empty;
            empShift.EmployeeID = new Guid(hdnEmployeeId.Value);
            empShift.Date = DateTime.ParseExact(row.Cells[0].Text, Constants.DATE_PATTERN,null);
            empShift.LastUser = employeeId;

            //explorer shiftID
            for (int j = 1; j < row.Cells.Count; j++)
            {
                CheckBox chk = (CheckBox)row.Cells[j].FindControl("chkShift" + j);
                //if check, add "1", otherwise add "0" into ShiftID
                if (chk.Checked)
                    empShift.ShiftID += "1";
                else
                    empShift.ShiftID += "0";
            }

            //If there is one shift at least
            if (Int16.Parse(empShift.ShiftID)>0)
            {
                //add to list
                list.Add(empShift);
            }
        }
        
        //Check if list =0, add employeeID to list
        if (list.Count==0)
        {
            int intMonth = int.Parse(ddlMonth.SelectedValue);
            int intYear = int.Parse(ddlYear.SelectedValue);
            DateTime monthYearDDL = new DateTime(intYear, intMonth, 1);

            empShift = new EmployeeShift();
            empShift.EmployeeID = new Guid(hdnEmployeeId.Value);
            empShift.Date = monthYearDDL;
            empShift.ShiftID = "000";
            list.Add(empShift);
        }

        try
        {
            if (shiftBLL.GrantShift(list))
            {
                lblMsg.Text = "Lưu thành công! Vui lòng chờ...";
                lblMsg.Focus();
                
                lblMsg.Visible = true;
                //load list again
                LoadGrid(new Guid(hdnEmployeeId.Value));

                //redirect to search
                Session["Shift"] = "Shift";
                Response.AddHeader("REFRESH", "2;URL=" + Constants.EMPLOYEE_SEARCH);
            }
        }
        catch (Exception ex)
        {
            lblMsg.Visible = true;
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }      
        }
    }

    private string GetCurrentByDay(int day)
    {
        return (day).ToString().PadLeft(2, '0') + "-" + DateTime.Now.Month.ToString().PadLeft(2, '0')+"-"+DateTime.Now.Year.ToString();
    }

    /// <summary>
    /// Load data into 2 dropdownlist
    /// </summary>
    void LoadYearDDL()
    {
        int currentYear = DateTime.Now.Year;
        for (int i = (currentYear-3); i < (currentYear+3); i++)
        {
            ListItem item = new ListItem(i.ToString(), i.ToString());
            ddlYear.Items.Add(item);
        }
        ddlMonth.SelectedValue = DateTime.Now.Month.ToString().PadLeft(2,'0');
        ddlYear.SelectedValue = currentYear.ToString();
    }

    /// <summary>
    /// Row data bound
    /// </summary>
    /// <param name="e"></param>
    private void RowDataBound(GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            for (int i = 1; i < e.Row.Cells.Count; i++)
            {
                //Get shift
                string[] shift = e.Row.Cells[i].Text.Split('_');


                CheckBox chk = new CheckBox();
                chk.ID = "chkShift"+i;

                if (i == 1)
                {
                    chk.Checked = shift[1].Equals("1");
                    //save employeeShiftId to hidden
                    HiddenField hdnId = new HiddenField();
                    hdnId.ID = "hdnId";
                    hdnId.Value = shift[0];
                    e.Row.Cells[i].Controls.Add(hdnId);
                }
                else
                    chk.Checked = e.Row.Cells[i].Text.Equals("1");
                e.Row.Cells[i].Controls.Add(chk);

            }
        }
        else
        {
            e.Row.Cells[0].Text = "Ngày/Ca";
            e.Row.Cells[0].Width = 120;
            for (int i = 1; i < e.Row.Cells.Count; i++)
            {
                CheckBox chk = new CheckBox();
                chk.ID = "chkShiftHeader" + i;
                chk.Text = " Ca " + i;
                chk.CssClass = "margin_l29";
                e.Row.Cells[i].Controls.Add(chk);
                chk.Attributes.Add("onclick", "CheckAll('ctl00_ContentHolder_gvShift_ctl01_" + chk.ID + "')");
            }
        }
    
    }




    protected void btnSave_Click(object sender, ImageClickEventArgs e)
    {
        Save();
    }
    protected void btnReset_Click(object sender, ImageClickEventArgs e)
    {
        this.Page_Load(null,null);
    }
    protected void gvShift_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        RowDataBound(e);
    }

    protected void ddlMonth_TextChanged(object sender, EventArgs e)
    {
        LoadGrid(new Guid(hdnEmployeeId.Value));
        lblMsg.Visible = false;
    }

    protected void ddlYear_TextChanged(object sender, EventArgs e)
    {
        LoadGrid(new Guid(hdnEmployeeId.Value));
        lblMsg.Visible = false;
    }


    protected void btnCancel_Click(object sender, ImageClickEventArgs e)
    {
        //redirect to search page
        this.Context.Items["Menu"] = "SHIFT_GRANT";
        Server.Transfer(Constants.EMPLOYEE_SEARCH);
    }
}
